package org.lcc.Controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.lcc.Service.CertificateService;

import org.lcc.util.ApiResponseMe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/certificate")
@Tag(name = "证书管理", description = "证书下载、验证等接口")
@Slf4j

public class CertificateController {

    @Autowired
    private CertificateService certificateService;

    @GetMapping("/download/{certificateCode}")
    @Operation(summary = "下载证书", description = "根据证书编码下载证书PDF文件")
    public ResponseEntity<Resource> downloadCertificate(@PathVariable String certificateCode) {
        try {
            Resource resource = certificateService.getCertificatePdf(certificateCode);
            
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_PDF)
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"certificate-" + certificateCode + ".pdf\"")
                    .body(resource);
        } catch (Exception e) {
            log.error("下载证书失败", e);
            return ResponseEntity.notFound().build();
        }
    }
    
    @GetMapping("/verify/{certificateCode}")
    @Operation(summary = "验证证书", description = "验证证书的真实性")
    public ApiResponseMe verifyCertificate(@PathVariable String certificateCode) {
        try {
            boolean isValid = certificateService.verifyCertificate(certificateCode);
            if (isValid) {
                return ApiResponseMe.success("证书有效");
            } else {
                return ApiResponseMe.error(400, "证书无效或已被撤销");
            }
        } catch (Exception e) {
            log.error("验证证书失败", e);
            return ApiResponseMe.error(400, "验证证书失败: " + e.getMessage());
        }
    }

    @GetMapping("/student/certificate/list")
    @Operation(summary = "获取学生证书列表", description = "分页获取学生的证书列表")
    public ApiResponseMe getStudentCertificates(
            @RequestParam String studentId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "8") Integer pageSize,
            @RequestParam(required = false) String keyword) {
        try {
            Map<String, Object> result = certificateService.getStudentCertificates(studentId, pageNum, pageSize, keyword);
            log.info("获取学生证书列表成功{}",  result);
            return ApiResponseMe.success(result);
        } catch (Exception e) {
            log.error("获取学生证书列表失败", e);
            return ApiResponseMe.error(500, "获取学生证书列表失败: " + e.getMessage());
        }
    }

} 